package com.lovepick;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.RouteOverlay;
import com.lovepick.adapter.OrderAdapter;
import com.lovepick.bean.Order;
import com.lovepick.fragment.MsgFragment;
import com.lovepick.http.HttpThread;
import com.lovepick.map.MapHelper;
import com.lovepick.map.PathOverlay;
import com.lovepick.util.BaseUtils;
import com.lovepick.util.Constant;
import com.lovepick.util.NumberPickerDialog;
import com.lovepick.util.OrderState;

/**
 * @author Liutong
 *
 * <h1>用户的推荐订单及地图查看</h1>
 *
 * <h2>以乘客身份发布</h2>
 * <p>用户以乘客身份发布订单后获得推荐的司机订单, 该类在地图上显示乘客与司机的订单信息.</p>
 * <ul>
 * 	<li>若推荐司机中有合适的, 乘客可以和司机商讨价格,
 *     	达成一致后乘客可以修改商讨后的价格, 之后向该司机申请订单.</li>
 *
 * 	<li>申请发出后乘客需要在订单管理中查看该订单的状态,
 *     	如果司机接受了订单申请, 在订单管理界面中会有显示.</li>
 * </ul>
 *
 * <h2>以司机身份发布</h2>
 * <p>用户以司机身份发布订单后获得推荐的乘客订单, 该类在地图上显示司机与乘客的订单信息.</p>
 * <ul>
 * 	<li>司机只能看到有哪些合适的乘客, 但司机不能主动向乘客发起申请</li>
 * 	<li>司机只能等待乘客向自己申请订单</li>
 * </ul>
 *
 */
public class MapView2Activity extends MapActivity
{
	private MapHelper mMapHelper;
	private RouteOverlay mRouteOverlay = null;
	private PathOverlay mPathOverlay = null;

	private static final String MAP_TAG = "MapViewActivity";
	private static final int REQUEST_CODE_APPLY = 1;

	private TextView txvMySrc;
	private TextView txvMyDest;
	private TextView txvMyCount;
	private TextView txvMyMoney;
	private TextView txvMyGoTime;
	private ImageView imgMyState;

	private TextView txvRecmdUser;
	private TextView txvRecmdSrc;
	private TextView txvRecmdDest;
	private TextView txvRecmdCount;
	private TextView txvRecmdMoney;
	private TextView txvRecmdGoTime;

	private TextView txvMyTitle;
	private TextView txvRecmdTitle;

	private TextView btnApply;
	private ImageButton btnMsg;
	private ImageButton btnCall;
	private TextView btnRecmdList;
	private LinearLayout mOrderInfos;
	private LinearLayout mOtherInfos;

	private Order mMyOrder;
	private Order mSelectedRecmdOrder;
	private OrderAdapter mAdapter = null;
	private List<Order> mRecmdOrders = null;

	private MapView mMapView;
	private MapHandler mHandler = null;
	private HttpThread mThread = null;

	private String mJson;
	private String mRole;
	private boolean isInfoVisible = true;
	private ProgressDialog mDialog = null;
	private boolean isFromRelease = true;

	@Override
	public void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		setContentView(R.layout.map);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		findViews();
		btnApply.setVisibility(View.GONE);
		btnMsg.setVisibility(View.GONE);
		btnCall.setVisibility(View.GONE);
		mOtherInfos.setVisibility(View.GONE);
		mDialog = new ProgressDialog(this);
		mRole = this.getIntent().getBundleExtra("bundle")
				.getString(Constant.ARG_ROLE);
		mJson = this.getIntent().getBundleExtra("bundle")
				.getString(Constant.ARG_RECMD_JSON);
		isFromRelease = this.getIntent().getBundleExtra("bundle")
				.getBoolean(Constant.ARG_IS_FROM_RELEASE);
		Log.i(MAP_TAG, "###isFromRelease=" + isFromRelease + "###");

		if (mRole.equals(Constant.PASSENGER))
		{
			// 用户当前身份是乘客
			txvMyTitle.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.ic_passenger, 0, 0, 0);

			// 推荐的是司机
			txvRecmdTitle.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.ic_driver, 0, 0, 0);

		}
		else
		{
			// 用户当前身份是司机
			txvMyTitle.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.ic_driver, 0, 0, 0);

			// 推荐的是乘客
			txvRecmdTitle.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.ic_passenger, 0, 0, 0);
		}

		mRecmdOrders = BaseUtils.getOrders(mJson, isFromRelease);

		if (null == mRecmdOrders)
		{
			Log.i(MAP_TAG, "mRecmdOrders null");
			mRecmdOrders = new ArrayList<Order>();
		}
		mAdapter = new OrderAdapter(this, mRecmdOrders);
		mHandler = new MapHandler(MapView2Activity.this);
		GlobalApp.getInstance().getMapManager().start();
		super.initMapActivity(GlobalApp.getInstance().getMapManager());

		Log.i(MAP_TAG, "initMap start");
		initMap();
		mMyOrder = GlobalApp.getInstance().getCurrentOrder();
		if (mMyOrder != null)
		{
			txvMySrc.setText(mMyOrder.getSrc());
			txvMyDest.setText(mMyOrder.getDest());
			txvMyGoTime.setText(mMyOrder.getGoTime());
			txvMyMoney.setText(String.valueOf(mMyOrder.getMoney()));
			txvMyCount.setText(String.valueOf(mMyOrder.getCount()));
			imgMyState.setImageDrawable(null);
			int mycolor = getResources().getColor(R.color.red_dark);
			searchRoute(mMyOrder, mycolor);
		}
		else
		{
			BaseUtils.showToast(getApplicationContext(), "没有我的路线!");
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.map, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case android.R.id.home:
				finish();
				break;

			case R.id.menu_orderinfos:
				showOrderInfos(item);
				return true;

			case R.id.menu_refresh:
				refreshRecmd(item);
				return true;

		}
		return super.onOptionsItemSelected(item);
	}

	private void findViews()
	{
		mOrderInfos = (LinearLayout) this.findViewById(R.id.map_order_infos);
		mOtherInfos = (LinearLayout) this.findViewById(R.id.map_infos_recmd);

		txvMySrc = (TextView) this.findViewById(R.id.order_item_mine_src);
		txvMyDest = (TextView) this.findViewById(R.id.order_item_mine_dest);
		txvMyCount = (TextView) this.findViewById(R.id.order_item_mine_count);
		txvMyMoney = (TextView) this.findViewById(R.id.order_item_mine_money);
		txvMyGoTime = (TextView) this.findViewById(R.id.order_item_mine_gotime);
		imgMyState = (ImageView) this.findViewById(R.id.order_item_mine_state);

		txvRecmdSrc = (TextView) this.findViewById(R.id.order_item_others_src);
		txvRecmdDest = (TextView) this.findViewById(R.id.order_item_others_dest);
		txvRecmdUser = (TextView) this.findViewById(R.id.order_item_others_user);
		txvRecmdGoTime = (TextView) this.findViewById(R.id.order_item_others_gotime);
		txvRecmdMoney = (TextView) this.findViewById(R.id.order_item_others_money);
		txvRecmdCount = (TextView) this.findViewById(R.id.order_item_others_count);

		txvMyTitle = (TextView) this.findViewById(R.id.txv_map_mine_title);
		txvRecmdTitle = (TextView) this.findViewById(R.id.txv_map_recmd_title);

		btnApply = (TextView) this.findViewById(R.id.map_btn_apply);
		btnMsg = (ImageButton) this.findViewById(R.id.map_btn_message);
		btnCall = (ImageButton) this.findViewById(R.id.map_btn_call);
		btnRecmdList = (TextView) this.findViewById(R.id.map_btn_recmd_list);
	}

	private void initMap()
	{
		mMapView = (MapView) this.findViewById(R.id.map_view);
		mMapView.setBuiltInZoomControls(true);
		//mMapView.setDrawOverlayWhenZooming(true);
		mRouteOverlay = new RouteOverlay(MapView2Activity.this, mMapView);
	}

	/**
	 * 控制订单信息(司机与乘客)部分的显示和隐藏,<br>
	 * 隐藏后可以使地图有更大的视野.
	 *
	 * @param item	actionbar中的按钮项
	 */
	private void showOrderInfos(MenuItem item)
	{
		if (isInfoVisible)
		{
			// 隐藏订单信息
			isInfoVisible = false;
			item.setIcon(R.drawable.menu_expand);
			item.setTitle(R.string.menu_expand);
			mOrderInfos.setVisibility(View.GONE);
		}
		else
		{
			// 显示订单信息
			isInfoVisible = true;
			item.setIcon(R.drawable.menu_collapse);
			item.setTitle(R.string.menu_collapse);
			mOrderInfos.setVisibility(View.VISIBLE);
		}
	}

	public void refreshRecmd(MenuItem item)
	{
		String url = "";
		url += "?test=test";
		url += "&slat=" + mMyOrder.getSlat();
		url += "&slng=" + mMyOrder.getSlng();
		url += "&dlat=" + mMyOrder.getDlat();
		url += "&dlng=" + mMyOrder.getDlng();
		url += "&goTime=" + mMyOrder.getGoTime();
		url += "&offset=" + mMyOrder.getOffset();

		try
		{
			btnApply.setVisibility(View.GONE);
			btnMsg.setVisibility(View.GONE);
			btnCall.setVisibility(View.GONE);
			mOtherInfos.setVisibility(View.GONE);
			btnRecmdList.setEnabled(false);
			url = java.net.URLEncoder.encode(url, "UTF-8");
			url = Constant.HTTP_URL_ORDER_RECOMMED + mRole + url;
			mThread = new HttpThread(mHandler, Constant.HTTP_METHOD_GET, url, null);
			mThread.start();
			BaseUtils.showToast(this, R.string.refresh_recmd);
		}
		catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			BaseUtils.showToast(this, R.string.no_recmd);
		}
	}


	/**
	 * 搜索订单的路线, 并在地图上显示
	 *
	 * @param order 订单数据
	 * @param color 绘制路线的颜色
	 */
	private void searchRoute(Order order, int color)
	{
		Log.i(MAP_TAG, "----searchRoute-----");
		if (null == order)
		{
			BaseUtils.showToast(this, R.string.search_rout_none);
		}
		else
		{
			List<GeoPoint> points = order.getPoints();
			if ((null == points) || (0 == points.size()))
			{
				Log.i(MAP_TAG, "###路线信息中没有保存规划点, 搜索并绘制路线###");
				GeoPoint start = new GeoPoint((int)(order.getSlat()*1E6), (int)(order.getSlng()*1E6));
				GeoPoint end = new GeoPoint((int)(order.getDlat()*1E6), (int)(order.getDlng()*1E6));
				Log.i(MAP_TAG, "###start=" + start.toString());
				Log.i(MAP_TAG, "###end=" + end.toString());
				mMapHelper = new MapHelper(GlobalApp.getInstance().getMapManager(), mHandler);
				mMapHelper.searchDrivingRoute(start, end);
				mDialog.setTitle(R.string.dialog_title_search_route);
				mDialog.setMessage(getResources().getString(R.string.dialog_msg_search_route));
				mDialog.show();
			}
			else
			{
				Log.i(MAP_TAG, "###路线信息中已有规划点, 使用这些规划点绘制路线###");
				mPathOverlay = new PathOverlay(mMapView.getProjection(), points, color);
				mMapView.getOverlays().add(mPathOverlay);
				mMapView.invalidate();
			}

		}

	}

	public void modifyMyOrder(View v)
	{
		NumberPickerDialog.OnNumberSetListener callBack = new NumberPickerDialog.OnNumberSetListener()
		{

			@Override
			public void onNumberSet(int number)
			{
				// TODO Auto-generated method stub
				mMyOrder.setMoney(number);
				txvMyMoney.setText(String.valueOf(number));
			}
		};
		NumberPickerDialog dialog = new NumberPickerDialog(v.getContext(),
				callBack,
				Order.MONEY_DEFAULT,
				Order.MONEY_MIN,
				Order.MONEY_MAX,
				R.string.dialog_title_modify,
				R.string.money_unit);
		dialog.show();
	}

	/**
	 * 显示推荐订单列表
	 *
	 * @param v
	 */
	public void showRecmdOrders(View v)
	{
		if ((null == mRecmdOrders) || (0 == mRecmdOrders.size()))
		{
			BaseUtils.showToast(this, R.string.get_recmd_fail);
		}
		else
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
			builder.setTitle(R.string.dialog_title_choose_recmd_order);
			if (mRole.equals(Constant.PASSENGER))
			{
				builder.setIcon(R.drawable.ic_driver);
			}
			else
			{
				builder.setIcon(R.drawable.ic_passenger);
			}
			builder.setAdapter(mAdapter, new DialogInterface.OnClickListener()
			{

				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					// TODO Auto-generated method stub
					mSelectedRecmdOrder = mRecmdOrders.get(which);
					txvRecmdUser.setText(mSelectedRecmdOrder.getNickName());
					txvRecmdSrc.setText(mSelectedRecmdOrder.getSrc());
					txvRecmdDest.setText(mSelectedRecmdOrder.getDest());
					txvRecmdGoTime.setText(mSelectedRecmdOrder.getGoTime());
					txvRecmdMoney.setText(String.valueOf(mSelectedRecmdOrder.getMoney()));
					txvRecmdCount.setText(String.valueOf(mSelectedRecmdOrder.getCount()));

					if (mRole.equals(Constant.PASSENGER))
					{
						btnApply.setVisibility(View.VISIBLE);
					}
					else
					{
						btnApply.setVisibility(View.GONE);
					}
					btnMsg.setVisibility(View.VISIBLE);
					btnCall.setVisibility(View.VISIBLE);

					mOtherInfos.setVisibility(View.VISIBLE);
					searchRoute(mSelectedRecmdOrder, getResources().getColor(R.color.blue_dark));
				}
			});
			builder.create().show();
		}
	}

	/**
	 * 申请订单操作
	 *
	 * @param v
	 */
	public void applyOrder(View v)
	{
		Intent intent = new Intent(MapView2Activity.this, ApplyDialogActivity.class);
		if (mRole.equals(Constant.PASSENGER))
		{
			intent.putExtra("passenger", mMyOrder.getNickName());
			intent.putExtra("driver", mSelectedRecmdOrder.getNickName());
		}
		else
		{
			intent.putExtra("passenger", mSelectedRecmdOrder.getNickName());
			intent.putExtra("driver", mMyOrder.getNickName());
		}
		intent.putExtra("count", mMyOrder.getCount());
		intent.putExtra("money", mMyOrder.getMoney());
		intent.putExtra("src", mMyOrder.getSrc());
		intent.putExtra("dest", mMyOrder.getDest());
		intent.putExtra("gotime", mMyOrder.getGoTime());
		intent.putExtra("passengerRouteID", mMyOrder.getOrderID());
		intent.putExtra("driverOrderID", mSelectedRecmdOrder.getOrderID());
		startActivityForResult(intent, REQUEST_CODE_APPLY);

	}

	/**
	 * 向选中的推荐列表的用户发送消息
	 * @param view
	 */
	public void sendMsg(View view)
	{
		GlobalApp.getInstance().saveRecmdOrder(mSelectedRecmdOrder);
		Intent intent = new Intent(this, MsgActivity.class);
		Bundle data = new Bundle();
		data.putInt(MsgFragment.ARG_USERID, mSelectedRecmdOrder.getUserID());
		data.putString(MsgFragment.ARG_NICKNAME, mSelectedRecmdOrder.getNickName());
		intent.putExtra("bundle_msg", data);
		startActivity(intent);
	}

	/**
	 * 向选中的推荐订单用户打电话
	 * @param view
	 */
	public void callPhone(View view)
	{
		BaseUtils.callPhone(this, mSelectedRecmdOrder.getPhone());
	}

	@Override
	protected void onPause()
	{
		GlobalApp.getInstance().getMapManager().stop();
		super.onPause();
	}

	@Override
	protected void onResume()
	{
		GlobalApp.getInstance().getMapManager().start();
		super.onResume();
	}

	@Override
	protected boolean isRouteDisplayed()
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (requestCode == REQUEST_CODE_APPLY)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				BaseUtils.showToast(this, R.string.apply_success);
				mMyOrder.setState(OrderState.APPLYING);
				mSelectedRecmdOrder.setState(OrderState.APPLYING);
				mSelectedRecmdOrder.setCount(mSelectedRecmdOrder.getCount() - mMyOrder.getCount());
				txvRecmdCount.setText(String.valueOf(mSelectedRecmdOrder.getCount() - mMyOrder.getCount()));
				imgMyState.setImageResource(R.drawable.ic_state_applying);
			}
			else {
				BaseUtils.showToast(this, R.string.apply_fail);
			}
		}

	}

	private static class MapHandler extends Handler
	{
		private WeakReference<MapView2Activity> mReference;
		private MapView2Activity mActivity;

		public MapHandler(MapView2Activity activity)
		{
			mReference = new WeakReference<MapView2Activity>(activity);
		}

		@Override
		public void handleMessage(Message msg)
		{
			mActivity = mReference.get();
			switch (msg.what)
			{
				case MapHelper.DRIVE_COMPLETE:
					mActivity.mDialog.dismiss();
					MKDrivingRouteResult result = mActivity.mMapHelper.getDrivingRouteResult();
					if (null == result)
					{
						Log.i(MAP_TAG, "###路线搜索结果为空!###");
						BaseUtils.showToast(mActivity, R.string.search_route_fail);
					}
					else
					{
						Log.i(MAP_TAG, "###查找到路线!###");
						BaseUtils.showToast(mActivity, R.string.search_route_success);
						mActivity.mRouteOverlay.setData(result.getPlan(0).getRoute(0));
						mActivity.mMapView.getOverlays().add(mActivity.mRouteOverlay);
						mActivity.mMapView.invalidate();
						Log.i(MAP_TAG, "add RouteOverlay!");
					}
					break;

				case Constant.MSG_HTTP_SUCCESS:

					String httpResult = msg.getData().getString(Constant.HTTP_RESULT);
					httpResult = httpResult.replace("\\\"", "\"")		// \" --> "
							.replace("\"[", "[")						// "[ --> [
							.replace("]\"", "]")						// ]" --> ]
							.replace("\"points\":\"\"", "\"points\":[]");	// "points":""
																			// -->
																			// "points:":[]
					if (httpResult.startsWith(Constant.JSON_ARRAY_START))
					{
						List<Order> tmp = BaseUtils.getOrders(httpResult, false);

						if (null == tmp)
						{
							Log.i(MAP_TAG, "tmp null");
							BaseUtils.showToast(mActivity, R.string.refresh_recmd_fail);
						}
						else {
							mActivity.mJson = httpResult;
							mActivity.mRecmdOrders = tmp;
							mActivity.mAdapter = new OrderAdapter(mActivity, mActivity.mRecmdOrders);
							BaseUtils.showToast(mActivity, R.string.refresh_recmd_success);
						}
					}
					else
					{
						BaseUtils.showToast(mActivity, R.string.refresh_recmd_fail);
					}
					mActivity.btnApply.setVisibility(View.GONE);
					mActivity.btnMsg.setVisibility(View.GONE);
					mActivity.btnCall.setVisibility(View.GONE);
					mActivity.mOtherInfos.setVisibility(View.GONE);
					mActivity.btnRecmdList.setEnabled(true);
					break;

				case Constant.MSG_HTTP_ERROR:
					mActivity.mDialog.dismiss();
					BaseUtils.showToast(mActivity, R.string.network_connnect_fail);
					break;

				default:
					mActivity.mDialog.dismiss();
					break;
			}
		}

	}
}
